package com.josework.springhelloworld.entity.person;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    String getName(){
        return name;
    }
    int getAge(){
        return age;
    }

    @Override
    public String toString() {
        return name;
    }

    public static void main(String[] args) {
        List<Person> persons =
                Arrays.asList(
                        new Person("Max", 18),
                        new Person("Peter", 23),
                        new Person("Pamela", 23),
                        new Person("David", 12));

        Map<Integer, List<Person>> personByAge = persons.stream().collect(Collectors.groupingBy(Person::getAge));

        personByAge.forEach(
                (age,p)-> System.out.printf("age %s: %s \n",age,p)
        );

        Double avgAge = persons.stream().collect(Collectors.averagingInt(Person::getAge));

//        String in_germany_ = persons.stream()
//                .filter(p -> p.getAge() >= 18)
//                .map(Person::getName)
//                .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));
//        System.out.println(in_germany_);

        Map<Integer, String> map = persons.stream()
                .collect(Collectors.toMap(
                        Person::getAge,
                        Person::getName,
                        (name1, name2) -> name1 + "," + name2
                ));

        System.out.println(map);

        String s1 = "s1";
        String s2 ="s2";
        StringJoiner stringJoiner = new StringJoiner(" | ");
        StringJoiner add1 = stringJoiner.add(s1);
        StringJoiner stringJoiner2 = new StringJoiner(" | ");
        StringJoiner add2 = stringJoiner2.add(s2);
        String s = add1.merge(add2).toString();


        //Collector.of()创建一个新的收集器。
        Collector<Person, StringJoiner, String> personNameCollector =
                Collector.of(
                        () -> new StringJoiner(" | "),          // supplier 供应器
                        (j, p) -> j.add(p.name.toUpperCase()),  // accumulator 累加器
                        StringJoiner::merge,               // combiner 组合器
                        StringJoiner::toString);
        String names = persons.stream().collect(personNameCollector);
        System.out.println(names);



    }

}
